package com.zxs.seckillservice.customer;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.zxs.constant.Constants;
import com.zxs.entity.Goods;
import com.zxs.entity.Orders;
import com.zxs.seckillservice.service.impl.GoodsServiceImpl;
import com.zxs.seckillservice.service.impl.OrderServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;


/**
 * 订单延迟消息的消费者
 */
@Component
public class OrderDelayCustomer {

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private OrderServiceImpl orderService;

    @Resource
    private GoodsServiceImpl goodsService;

    @Resource
    private RedisTemplate redisTemplate;

    @Transactional
    @RabbitListener(queues = {Constants.QUEUE_DELAY_NAME})
    public void customerMessage(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            //获取订单ID
            Integer orderId = objectMapper.readValue(message.getBody(), Integer.class);

            //查询订单状态
            Orders order = orderService.getById(orderId);
            //订单状态为0，未支付
            if (order.getStatus() == 0) {
                //更改订单状态为2 超时未支付
                UpdateWrapper<Orders> ordersUpdateWrapper = new UpdateWrapper<>();
                ordersUpdateWrapper.set("status", 2);
                ordersUpdateWrapper.eq("id", orderId);
                boolean update = orderService.update(ordersUpdateWrapper);
                if (update) {
                    //修改订单状态成功
                    //通过商品ID查询商品信息
                    Goods goods = goodsService.getById(order.getGoodsId());
                    //商品的库存+1
                    UpdateWrapper<Goods> goodsUpdateWrapper = new UpdateWrapper<>();
                    goodsUpdateWrapper.set("store", goods.getStore() + 1);
                    goodsUpdateWrapper.eq("id", goods.getId());
                    boolean updateGoods = goodsService.update(goodsUpdateWrapper);
                    //redis中库存加+1
                    redisTemplate.opsForValue().increment(Constants.REDIS_STORE + goods.getId(), 1);
                    //修改Redis中商品的结果  //redis:result:2:20030211
                    Orders oldOrders =(Orders) redisTemplate.opsForValue().get(Constants.REDIS_RESULT + order.getGoodsId() + ":" + order.getUid());
                    oldOrders.setStatus(2);
                    redisTemplate.opsForValue().set(Constants.REDIS_RESULT + order.getGoodsId() + ":" + order.getUid(),oldOrders);
                    if (updateGoods) {
                        //库存修改成功，确认消息
                        channel.basicAck(deliveryTag, false);
                    }else {
                        throw new RuntimeException("库存修改失败");
                    }
                }else {
                    throw new RuntimeException("修改订单失败");
                }
            }else {
                //已经支付,拒绝消息
                channel.basicReject(deliveryTag, false);
            }

        } catch (IOException e) {
            int count = 0;
            while (count < 3) {
                try {
                    channel.basicNack(deliveryTag, false, true);
                    count++;
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
            channel.basicReject(deliveryTag, false);

        }
    }

}
